import java.util.concurrent.CountDownLatch;

/**
 * Created with IntelliJ IDEA.
 * Description:CountDownLatch 实现多任务打包执行。
 * Date: 2024-09-04
 * Time: 22:27
 */
public class CountDownLatchExample {
    static class Worker implements Runnable {
        private final CountDownLatch latch;
        private final int workerId;

        Worker(CountDownLatch latch, int workerId) {
            this.latch = latch;
            this.workerId = workerId;
        }

        @Override
        public void run() {
            try {
                System.out.println("任务 "+this.workerId+"正在执行！");
                Thread.sleep((long) (Math.random() * 1000));
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                latch.countDown();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(10);

        for (int i = 0; i < 10; i++) {
            int id = i;
            new Thread(new Worker(latch,id)).start();
        }

        latch.await();

        System.out.println("所有线程执行完毕，主线程开始执行");
    }
}
